﻿package com.cloneoner.test
{
	import fr.digitas.flowearth.debug.FPS;
	import flash.display.DisplayObject;
	import flash.display.Loader;
	import flash.display.Sprite;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.net.URLRequest;
	import flash.system.LoaderContext;

	[SWF(backgroundColor="#333333", frameRate="60", width="900", height="600")]
	
	public class Main extends Sprite
	{
		
		public function Main()
		{
			if ( stage)
				_init();
			else
				addEventListener(Event.ADDED_TO_STAGE, _init);
		}

		private function _init(event : Event = null) : void
		{
			removeEventListener(Event.ADDED_TO_STAGE, _init);

			stage.scaleMode = StageScaleMode.NO_SCALE;
			stage.align = StageAlign.TOP_LEFT;

			_build();
		}


		private function _build() : void
		{
			_context = new LoaderContext();
			
			_bmpdm = new BmpMediaViewer(600, 400);
			_bmpdm.x = _bmpdm.y = 100;
			
			var s:Sprite = new Sprite();
			s.graphics.beginFill(0);
			s.graphics.drawRect(500, 10, 50, 50);
			s.graphics.endFill();
			addChild(s);
			
			addChild(new FPS());
			
			s.addEventListener(MouseEvent.CLICK, _onNext);
			_onNext(null);
		}

		private function _onNext(event : MouseEvent) : void
		{
			++_index;
			
			if( _index >= _a.length ) _index = 0;
			
			_load("imgs/"+_a[_index]);
		}
		
		private function _load(pURL:String):void
		{
			_cleanLoader();
			
			_loader = new Loader();
			_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, _onLoaded);
			
			_loader.load(new URLRequest(pURL), _context);
		}
		
		private function _onLoaded(event : Event) : void
		{
			var content:DisplayObject = _loader.content;
			
			var d:Number;
			
			if( !contains(_bmpdm))
			{
				addChildAt(_bmpdm, 0);
				d = 0;
			}
			else
			{
				d = 2;
			}
			
			_bmpdm.add(content, d);
		}
		
		private function _cleanLoader() : void
		{
			if( !_loader ) return;
			
			_loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, _onLoaded);
			_loader.unload();
			_loader = null;
		}


		private var _loader : Loader;
		private var _context:LoaderContext;
		private var _bmpdm : BmpMediaViewer;
		
		private var _a:Array = ["img_01.jpg", "img_02.jpg", "img_03.jpg", "img_04.jpg", "img_05.jpg"];
		private var _index:int = -1;
	}
}
